package yto.freemarker.java8.dateapi;

import org.junit.Test;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.*;

/**
 * 传统的时间
 * <p>
 * 存在多线程安全的问题
 *
 * @author dongxing
 * @create 2018-06-23 17:47
 **/
public class TestSimpleDateFormater {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Callable<Date> callable = new Callable<Date>() {
            @Override
            public Date call() throws Exception {
                return simpleDateFormat.parse("2018-11-23 12:12:12");
            }
        };

        ExecutorService pool = Executors.newFixedThreadPool(10);

        List<Future<Date>> list = new ArrayList<>();

        for (int i = 0; i < 10; i++) {
            list.add(pool.submit(callable));
        }

        for (Future<Date> dateFuture : list) {
            System.out.println(dateFuture.get());
        }

    }


    /**
     * 手动线程安全
     * 解决了时间的安全问题
     */
    @Test
    public void test1() throws ExecutionException, InterruptedException {

        Callable<Date> callable = new Callable<Date>() {
            @Override
            public Date call() throws Exception {
                return DateFormatThreadLocal.convert("2018-11-23 12:12:12");
            }
        };

        ExecutorService pool = Executors.newFixedThreadPool(10);

        List<Future<Date>> list = new ArrayList<>();

        for (int i = 0; i < 10; i++) {
            list.add(pool.submit(callable));
        }

        for (Future<Date> dateFuture : list) {
            System.out.println(dateFuture.get());
        }

        pool.shutdown();


    }

    /**
     * jdk1.8解决了时间安全问题
     * 解决了时间的安全问题
     */
    @Test
    public void test2() throws ExecutionException, InterruptedException {

        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        Callable<LocalDate> callable = new Callable<LocalDate>() {
            @Override
            public LocalDate call() throws Exception {
                return LocalDate.parse("2018-11-23 12:12:12", dtf);
            }
        };

        ExecutorService pool = Executors.newFixedThreadPool(10);

        List<Future<LocalDate>> list = new ArrayList<>();

        for (int i = 0; i < 10; i++) {
            list.add(pool.submit(callable));
        }

        for (Future<LocalDate> dateFuture : list) {
            System.out.println(dateFuture.get());
        }

        pool.shutdown();


    }

}
